<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col>
        <!-- 搜索表单 -->
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable style="width: 200px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="queryParams.nickname" placeholder="请输入昵称" clearable style="width: 200px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable style="width: 200px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px">
              <el-option label="正常" :value="1" />
              <el-option label="停用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

<!--                                        后续要改一下 添加权限的指令关系    -->
        <!-- 操作按钮 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
          </el-col>
        </el-row>

        <!-- 用户表格 -->
        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="用户名" align="center" prop="username" />
          <el-table-column label="昵称" align="center" prop="nickname" />
          <el-table-column label="手机号" align="center" prop="phone" />
          <el-table-column label="性别" align="center" prop="gender">
            <template #default="scope">
              <span>{{ scope.row.gender === 1 ? '男' : scope.row.gender === 0 ? '女' : '未知' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                {{ scope.row.status === 1 ? '正常' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createdAt" />
          <el-table-column label="操作" align="center" width="200">
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">编辑</el-button>
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
              <el-button link type="warning" icon="User" @click="handleAssignRole(scope.row)">分配角色</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 新增/编辑用户弹窗 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form :model="form" :rules="rules" ref="userRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" maxlength="30" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称" maxlength="30" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" maxlength="20" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择">
            <el-option label="男" :value="1" />
            <el-option label="女" :value="0" />
            <el-option label="未知" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="!form.id" label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" type="password" maxlength="20" show-password />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-input v-model="form.avatar" placeholder="请输入头像URL" maxlength="255" />
        </el-form-item>
        <el-form-item label="简介" prop="bio">
          <el-input v-model="form.bio" type="textarea" placeholder="请输入简介" maxlength="255" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配角色弹窗 -->
    <el-dialog title="分配角色" v-model="roleDialogOpen" width="400px" append-to-body>
      <el-checkbox-group v-model="selectedRoleIds">
        <el-checkbox v-for="role in roleList" :key="role.id" :label="role.id">{{ role.name }}</el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAssignRole">保存</el-button>
          <el-button @click="roleDialogOpen = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, addUser, updateUser, delUser, getRoleList, getUserRoles, assignRole } from '@/api/user'
export default {
  data() {
    return {
      queryParams: { pageNum: 1, pageSize: 10, username: '', nickname: '', phone: '', status: '' },
      userList: [],
      total: 0,
      loading: false,
      showSearch: true,
      open: false,
      title: '',
      form: {},
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
        gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      single: true,
      multiple: true,
      selectedRows: [],
      // 角色分配相关
      roleDialogOpen: false,
      roleList: [],
      selectedUserId: null,
      selectedRoleIds: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      listUser(this.queryParams).then(res => {
        this.userList = res.data.records
        this.total = res.data.total
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams = { pageNum: 1, pageSize: 10, username: '', nickname: '', phone: '', status: '' }
      this.getList()
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.form = { status: 1, gender: 2 }
      this.open = true
      this.title = '新增用户'
    },
    handleUpdate(row) {
      getUser(row ? row.id : this.selectedRows[0].id).then(res => {
        this.form = { ...res.data }
        this.open = true
        this.title = '编辑用户'
      })
    },
    handleDelete(row) {
      let id = row ? row.id : (this.selectedRows[0] && this.selectedRows[0].id)
      if (!id) {
        this.$message.warning('请选择要删除的用户')
        return
      }
      this.$confirm('确定要删除选中的用户吗？', '提示', { type: 'warning' }).then(() => {
        delUser(id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      })
    },
    submitForm() {
      this.$refs.userRef.validate(valid => {
        if (!valid) return
        if (!this.form.id) {
          addUser(this.form).then(() => {
            this.$message.success('新增成功')
            this.open = false
            this.getList()
          })
        } else {
          updateUser(this.form).then(() => {
            this.$message.success('修改成功')
            this.open = false
            this.getList()
          })
        }
      })
    },
    cancel() {
      this.open = false
    },
    // 角色分配
    handleAssignRole(row) {
      this.selectedUserId = row.id
      getRoleList().then(res => {
        this.roleList = res.data
        getUserRoles(row.id).then(r2 => {
          this.selectedRoleIds = r2.data
          this.roleDialogOpen = true
        })
      })
    },
    submitAssignRole() {
      assignRole({ userId: this.selectedUserId, roleIds: this.selectedRoleIds }).then(() => {
        this.$message.success('分配成功')
        this.roleDialogOpen = false
        this.getList()
      })
    }
  }
}
</script>
